// ****************************************************************************

// ****************************************************************************

#include "UDP_Observer.hpp"

#include <sstream>

// GenIO
#include "GenSocketManager.hpp"
#include "GenUDP_Connection.hpp"

// Utilities
#include "UtCast.hpp"
#include "UtInputBlock.hpp"
#include "UtLog.hpp"

#include "RegisterUDP_Observer.hpp"

// WSF
#include "WsfApplication.hpp"
#include "WsfApplicationExtension.hpp"
#include "WsfException.hpp"

#include "observer/WsfPlatformObserver.hpp"
#include "observer/WsfTrackObserver.hpp"
#include "observer/WsfSimulationObserver.hpp"
#include "observer/WsfAdvancedBehaviorObserver.hpp"
#include "observer/WsfBehaviorObserver.hpp"
#include "observer/WsfCommObserver.hpp"
#include "observer/WsfDisObserver.hpp"
#include "observer/WsfExchangeObserver.hpp"
#include "observer/WsfFuelObserver.hpp"
#include "observer/WsfMoverObserver.hpp"
#include "observer/WsfPlatformPartObserver.hpp"
#include "observer/WsfProcessorObserver.hpp"
#include "observer/WsfQuantumTaskerObserver.hpp"
#include "observer/WsfScriptStateMachineObserver.hpp"
#include "observer/WsfSensorObserver.hpp"
#include "observer/WsfTaskObserver.hpp"
#include "observer/WsfWeaponObserver.hpp"
#include "observer/WsfWeaponTaskObserver.hpp"
#include "observer/WsfZoneObserver.hpp"

#include "sensor/WsfSensor.hpp"

#include "WsfPlatform.hpp"
#include "WsfTrackManager.hpp"

#include "WsfSimulation.hpp"
#include "WsfTrack.hpp"

#include "WsfGroundMover.hpp"
#include "WsfAirMover.hpp"
#include "WsfSurfaceMover.hpp "
#include "WsfWaypoint.hpp"
//#include "UDPObserverPrivate.hpp"

// ****************************************************************************
// Public

static bool isInitPlatFormSides = false;

UDP_Observer::UDP_Observer()
   : mPort(14421),
     mRecvPort(14422),
     mAddress(),
     mConnectionPtr(nullptr)
{
}
UDP_Observer::UDP_Observer(const UDP_Observer& aSrc)
   : mPort(aSrc.mPort),
     mRecvPort(aSrc.mRecvPort),
     mAddress(aSrc.mAddress),
     mConnectionPtr(nullptr)
{
}
UDP_Observer& UDP_Observer::operator=(const UDP_Observer& aSrc)
{
   mPort = aSrc.mPort;
   mRecvPort = aSrc.mRecvPort;
   mAddress = aSrc.mAddress;
   mConnectionPtr = nullptr;
   return *this;
}
UDP_Observer::~UDP_Observer() noexcept
{
   Disconnect();
}

bool UDP_Observer::Initialize()
{
   if (mAddress.empty())
   {
      Disconnect();
      return true;
   }
   bool connected = false;

   mConnectionPtr = new GenUDP_Connection();
   connected = mConnectionPtr->Init(mAddress, mPort,mRecvPort);

 
   if (connected)
   {
        std::cout << "zhanglei:start recv thread.";

        //启动数据接收线程
        std::thread t([&]() {
            while (this->mConnectionPtr)
            {
                char aBuffer[1024];
                memset(aBuffer, '\0', 1024);

                int bytes = mConnectionPtr->ReceiveBuffer(3000, aBuffer, 1024);

                if (bytes > 0)
                {
                    InterfaceError result = DecodeMsg(std::string(aBuffer));
					SendPacket(result.errorInfo);
					//if(result.errorCode != 1)
                }
            }
        });

        t.detach();

		// WsfPlatformObserver 所有事件    
		mCallbacks.Add(WsfObserver::PlatformAdded(&GetSimulation()).Connect(&UDP_Observer::PlatformAdded, this));                                     //平台添加
		mCallbacks.Add(WsfObserver::PlatformDeleted(&GetSimulation()).Connect(&UDP_Observer::PlatformDeleted, this));                                 //平台删除

		// WsfSensorObserver 所有事件
		mCallbacks.Add(WsfObserver::SensorScanUpdated(&GetSimulation()).Connect(&UDP_Observer::SensorScanUpdated, this)); //传感器扫描更新

		// WsfSimulationObserver 所有事件
		mCallbacks.Add(WsfObserver::AdvanceTime(&GetSimulation()).Connect(&UDP_Observer::AdvanceTime, this)); //时间推进事件 一秒一推送
		mCallbacks.Add(WsfObserver::RequestTimeAdvance(&GetSimulation()).Connect(&UDP_Observer::RequestTimeAdvance, this)); //请求时间推进
		mCallbacks.Add(WsfObserver::SimulationClockRateChange(&GetSimulation()).Connect(&UDP_Observer::SimulationClockRateChange, this)); //仿真时钟速率变化
		mCallbacks.Add(WsfObserver::SimulationInitializing(&GetSimulation()).Connect(&UDP_Observer::SimulationInitializing, this)); //仿真初始化
		mCallbacks.Add(WsfObserver::SimulationStarting(&GetSimulation()).Connect(&UDP_Observer::SimulationStarting, this)); //仿真启动
		mCallbacks.Add(WsfObserver::SimulationPausing(&GetSimulation()).Connect(&UDP_Observer::SimulationPausing, this)); //仿真暂停
		mCallbacks.Add(WsfObserver::SimulationResuming(&GetSimulation()).Connect(&UDP_Observer::SimulationResuming, this)); //仿真恢复
		mCallbacks.Add(WsfObserver::SimulationComplete(&GetSimulation()).Connect(&UDP_Observer::SimulationComplete, this)); //仿真完成

		// WsfTrackObserver 所有事件
		mCallbacks.Add(WsfObserver::LocalTrackDropped(&GetSimulation()).Connect(&UDP_Observer::LocalTrackDropped, this)); //本地航迹丢弃
		mCallbacks.Add(WsfObserver::LocalTrackInitiated(&GetSimulation()).Connect(&UDP_Observer::LocalTrackInitiated, this)); //本地航迹创建
		mCallbacks.Add(WsfObserver::LocalTrackUpdated(&GetSimulation()).Connect(&UDP_Observer::LocalTrackUpdated, this)); //本地航迹更新
		mCallbacks.Add(WsfObserver::SensorTrackCoasted(&GetSimulation()).Connect(&UDP_Observer::SensorTrackCoasted, this)); //传感器航迹惯性推算
		mCallbacks.Add(WsfObserver::SensorTrackDropped(&GetSimulation()).Connect(&UDP_Observer::SensorTrackDropped, this)); //传感器航迹丢弃
		mCallbacks.Add(WsfObserver::SensorTrackInitiated(&GetSimulation()).Connect(&UDP_Observer::SensorTrackInitiated, this)); //传感器航迹创建
		mCallbacks.Add(WsfObserver::SensorTrackUpdated(&GetSimulation()).Connect(&UDP_Observer::SensorTrackUpdated, this)); //传感器航迹更新

		// WsfWeaponObserver
		mCallbacks.Add(WsfObserver::WeaponFireAborted(&GetSimulation()).Connect(&UDP_Observer::WeaponFireAborted, this)); //武器开火中止
		mCallbacks.Add(WsfObserver::WeaponFired(&GetSimulation()).Connect(&UDP_Observer::WeaponFired, this)); //武器开火
		mCallbacks.Add(WsfObserver::WeaponFireRequested(&GetSimulation()).Connect(&UDP_Observer::WeaponFireRequested, this)); //武器开火请求
		mCallbacks.Add(WsfObserver::WeaponPlatformPendingAdd(&GetSimulation()).Connect(&UDP_Observer::WeaponPlatformPendingAdd, this)); //武器平台待添加
		mCallbacks.Add(WsfObserver::WeaponHit(&GetSimulation()).Connect(&UDP_Observer::WeaponHit, this)); //武器命中
		mCallbacks.Add(WsfObserver::WeaponKilled(&GetSimulation()).Connect(&UDP_Observer::WeaponKilled, this)); //武器摧毁
		mCallbacks.Add(WsfObserver::WeaponMissed(&GetSimulation()).Connect(&UDP_Observer::WeaponMissed, this)); //武器未命中
   }
   else
   {
      auto out = ut::log::error() << "Could not connect to socket.";
      out.AddNote() << "Address: " << mAddress;
      out.AddNote() << "Port: " << mPort;
      
      delete mConnectionPtr;
      mConnectionPtr = nullptr;
   }
   return connected;
}
bool UDP_Observer::ProcessInput(UtInput& aInput)
{
   /** We are searching for a command of the form:
   udp_observer
      port      4321
      address   www.google.com
   end_udp_observer  */

   bool myCommand = false;
  
   if (aInput.GetCommand() == "udp_observer")
   {
      myCommand = true;

      
      UtInputBlock block(aInput);

      std::string command;
      while (block.ReadCommand(command))
      {
         if (command == "port")
         {
            aInput.ReadValue(mPort);

            mRecvPort = mPort + 1;  //自动设置接收端口号
         }
         else if (command == "address")
         {
            aInput.ReadValue(mAddress);
         }
         else
         {
            throw UtInput::UnknownCommand(aInput);
         }
      }
   }
   return myCommand;
}
void UDP_Observer::Disconnect()
{
   delete mConnectionPtr;
   mConnectionPtr = nullptr;
   mCallbacks.Clear();
}
void UDP_Observer::initPlatformSides()
{
	mPlatformSides.clear();
	size_t platFormCount = GetSimulation().GetPlatformCount();
	mPlatformSides.reserve(platFormCount);
	for (size_t i = 1; i <= platFormCount; i++) 
	{
		WsfPlatform* curPlatForm = GetSimulation().GetPlatformByIndex(i);
		if (!curPlatForm)
			continue;

		std::string side = curPlatForm->GetSide();
		mPlatformSides.emplace_back(static_cast<int>(i), side);
	}
}

////////////////////////////第一部分控制
UDP_Observer::InterfaceError UDP_Observer::DecodeMsg(std::string msg)
{
    //处理外部消息
    //首先对数据进行反序列化
    Json::Reader reader;
    Json::Value data;

    if (!reader.parse(msg, data))
        return InterfaceError(-1, "reader_error");
    try
    {
        std::string msgType = data["MsgType"].asString();

        ut::log::info() << "zhanglei:recv msg: "<< msgType;
        
		if (msgType == "SimStart")
			return HandleMsg_Start(data);

        if (msgType == "SimPause")
			return HandleMsg_Pause(data);

        if (msgType == "SimResume")
			return HandleMsg_Resume(data);

        if (msgType == "SimComplete")
			return HandleMsg_Complete(data);

		if (msgType == "PlatformLocationChange")
			return HandleMsg_LocationChange(data);

		if (msgType == "SimAdvanceTime")
			return HandleMsg_SimAdvanceTime(data);

		if (msgType == "SimClockRate")
			return HandleMsg_SimClockRate(data);

		if (msgType == "PlatformMoveTo")
			return HandleMsg_MoveTo(data);

		if (msgType == "AttackTarget")
			return HandleMsg_AttackTarget(data);

		if (msgType == "ControlSensor")
			return HandleMsg_ControlSensor(data);
	
	}
    catch (std::exception& e)
    {
        std::cout << "request format error:" << e.what() << std::endl;
		return InterfaceError(-1, "equest format error");
    }
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_Pause(Json::Value& data)
{
    WsfSimulation&  simulation = this->GetSimulation();

    if (simulation.GetState() == WsfSimulation::State::cACTIVE)
        simulation.Pause();
	return InterfaceError(1, "SimulationPauseFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_Resume(Json::Value& data)
{
    WsfSimulation& simulation = this->GetSimulation();

    if (simulation.GetState() == WsfSimulation::State::cACTIVE)
        simulation.Resume();
	return InterfaceError(1, "SimulationResumeFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_Start(Json::Value& data)
{
	GetSimulation().Start();
	return InterfaceError(1, "SimulationStartFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_Complete(Json::Value& data)
{
    WsfSimulation& simulation = this->GetSimulation();
    simulation.Complete(simulation.GetWallTime());
	return InterfaceError(1, "SimulationCompleteFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_LocationChange(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	int pid = data["PlatformID"].asInt();
	std::vector<double> loc;
	Json::Value locj = data["Location"];

	for (int i = 0; i < locj.size(); i++)
	{
		Json::Value element = locj[i];
		loc.push_back(element.asDouble());
	}

	if (loc.size() >= 3)
	{
		WsfPlatform* pptr = simulation.GetPlatformByIndex(pid);

		if (!pptr)
			return InterfaceError(-1, "LocationChangeError_GetPlatFormError");

		WsfMover* mvptr = pptr->GetMover();

		if (!mvptr)
			return InterfaceError(-1, "LocationChangeError_GetMoverError");

		pptr->SetLocationLLA(loc[0], loc[1], loc[2]);
		ut::log::info() << "mover";
		mvptr->ResetPosition(simulation.GetWallTime());
	}
	return InterfaceError(1, "SimulationLocationChangeFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_MoveTo(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	int pid = data["PlatformID"].asInt();
	WsfPlatform* pptr = simulation.GetPlatformByIndex(pid);
	if (!pptr) 
		return InterfaceError(-1, "MoveToError_GetPlatFormError");

	Json::Value waypointData = data["WayPoint"];
	if (!waypointData.isArray() || waypointData.size() < 3) 
		return InterfaceError(-1, "MoveToError_WaypointDataError");

	// 提取WayPoint参数
	double lat = waypointData[0].asDouble();   // 纬度
	double lon = waypointData[1].asDouble();   // 经度
	double alt = waypointData[2].asDouble();   // 海拔
	pptr->GetMover()->GoToLocation(simulation.GetWallTime(), lat, lon, alt);
	return InterfaceError(1, "SimulationMoveToFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_Speed(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	int pid = data["PlatformID"].asInt();
	WsfPlatform* pptr = simulation.GetPlatformByIndex(pid);
	if (!pptr)
		return InterfaceError(-1, "SpeedError_GetPlatFormError");;

	Json::Value waypointData = data["Speed"];
	double spd = data["Speed"].asDouble();  // 速度
	double acc = data["LinearAccel"].asDouble();  // 速度
	pptr->GetMover()->GoToSpeed(simulation.GetWallTime(), spd, acc, false);
	return InterfaceError(1, "SimulationSpeedFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_SimClockRate(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	double cRate = data["ClockRate"].asDouble();
	simulation.SetClockRate(cRate);
	return InterfaceError(1, "SimulationClockRateFinish");;
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_SimAdvanceTime(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	double advTime = data["AdvanceTime"].asDouble();
	simulation.AdvanceTime(simulation.GetWallTime() + advTime);
	return InterfaceError(1, "SimulationAdvanceTimeFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_AttackTarget(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	int pid = data["PlatformID"].asInt();
	WsfPlatform* pptr = simulation.GetPlatformByIndex(pid);
	if (!pptr)
		return InterfaceError(-1, "AttackTargetError_GetPlatFormError");

	//获取轨迹
	unsigned int localTrackCount = pptr->GetTrackManager().GetTrackCount();
	unsigned int rawTrackCount = pptr->GetTrackManager().GetRawTrackCount();
	ut::log::info() << "localTrackCount: " << localTrackCount;
	ut::log::info() << "rawTrackCount: " << rawTrackCount;
	if (localTrackCount < 1 && rawTrackCount < 1)
		return InterfaceError(-1, "AttackTargetError_NoTrack");
	WsfTrack* track = pptr->GetTrackManager().GetTrackEntry(localTrackCount - 1);

	//武器
	std::string weaponId = data["WeaponID"].asString();
	WsfWeapon* weapon = static_cast<WsfWeapon*>(pptr->FindComponent(weaponId));
	if (!weapon)
		return InterfaceError(-1, "AttackTargetError_NoWeapon");
	ut::log::info() << "weaponinfo: " << weapon->GetWeaponEffectsType();

	weapon->CueToTarget(GetSimulation().GetWallTime(), track);
	WsfWeapon::FireTarget fireTarget = WsfWeapon::FireTarget(track);
	WsfWeapon::FireOptions fireOptions = WsfWeapon::FireOptions();
	fireOptions.mWeaponComponentName = weaponId;

	WsfWeapon::FireResult ret = weapon->Fire(GetSimulation().GetWallTime() + 1, fireTarget, fireOptions);
	ut::log::info() << "attackTargetFinish";
	return InterfaceError(1, "AttackTargetFinish");
}
UDP_Observer::InterfaceError UDP_Observer::HandleMsg_ControlSensor(Json::Value& data)
{
	WsfSimulation& simulation = this->GetSimulation();
	int pid = data["PlatformID"].asInt();
	WsfPlatform* pptr = simulation.GetPlatformByIndex(pid);
	if (!pptr)
		return InterfaceError(-1, "ControlSensorError_GetPlatFormError");

	std::string sensorID = data["SensorID"].asString();
	WsfSensor* sensor = static_cast<WsfSensor*>(pptr->FindComponent(sensorID));
	if (!sensor)
		return InterfaceError(-1, "ControlSensorError_GetSensorError");

	std::string action = data["Action"].asString();
	if (action == "Open")
	{
		ut::log::info() << "SensorOpen";
		GetSimulation().TurnPartOn(GetSimulation().GetWallTime(), sensor);
		ut::log::info() << "SensorOpenSuccess?" << sensor->IsClassActive();
	}
	else if (action == "Close")
	{
		ut::log::info() << "sensorClose";
		GetSimulation().TurnPartOff(GetSimulation().GetWallTime(), sensor);
		ut::log::info() << "SensorOpenSuccess?" << sensor->IsClassActive();
	}
	ut::log::info() << "SensorFinish";
	return InterfaceError(1, "ControlSensorFinish");
}

////////////////////////////第二部分态势
void UDP_Observer::AdvanceTime(double aSimTime)
{
	// 检查是否到达整秒
	static double lastSecond = 0.0;
	int currentSecond = static_cast<int>(aSimTime);

	if (currentSecond > lastSecond)
	{
		if (!isInitPlatFormSides)
		{
			isInitPlatFormSides = true;
			initPlatformSides();
		}

		lastSecond = currentSecond;
		Json::Value simulationData = GenerateSimulationData(aSimTime);

		Json::FastWriter writer;
		ut::log::info() << "simulationDataOutput:" << simulationData;
		std::string jsonData = writer.write(simulationData);

		SendPacket(jsonData);
	}
}

////////////////////////////第三部分事件
void UDP_Observer::PlatformAdded(double aSimTime, WsfPlatform* aPlatformPtr)
{
	//获取经纬度信息
	double lat, lon, alt;
	aPlatformPtr->GetLocationLLA(lat, lon, alt);

	//获取姿态信息
	double heading, pitch, roll;
	aPlatformPtr->GetOrientationNED(heading, pitch, roll);

	//拼接json串
	Json::Value root;

	root["MsgType"] = Json::Value("PlatformAdded");
	root["WallTime"] = Json::Value(aSimTime);

	root["PlatformID"] = Json::Value((int)aPlatformPtr->GetIndex());
	root["PlatformName"] = Json::Value(aPlatformPtr->GetName());
	root["PlatformType"] = Json::Value(aPlatformPtr->GetType());
	root["PlatformSide"] = Json::Value(aPlatformPtr->GetSide());

	//分组
	std::string groupsInfo;
	for (auto str : aPlatformPtr->GetGroups().GetGroupList())
	{
		groupsInfo.append(str.GetString());
	}
	if (aPlatformPtr->GetGroups().GetGroupList().size() > 0)
		root["PlatformGroup"] = Json::Value(aPlatformPtr->GetGroups().GetGroupList()[0].GetString());

	//传感器
	root["Location"].append(lat);
	root["Location"].append(lon);
	root["Location"].append(alt);

	root["Orientation"].append(heading);
	root["Orientation"].append(pitch);
	root["Orientation"].append(roll);

	Json::FastWriter fw;
	std::string msg = fw.write(root);

	SendPacket(msg);
}
void UDP_Observer::PlatformDeleted(double aSimTime, WsfPlatform* aPlatformPtr)
{
	//拼接json串
	Json::Value root;

	root["MsgType"] = Json::Value("PlatformDelete");
	root["WallTime"] = Json::Value(aSimTime);

	root["PlatformID"] = Json::Value((int)aPlatformPtr->GetIndex());
	root["PlatformName"] = Json::Value(aPlatformPtr->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);

	SendPacket(msg);
}
void UDP_Observer::MoverUpdated(double aSimTime, WsfMover* mvr)
{
	WsfPlatform* aPlatformPtr = mvr->GetPlatform();

	if (!aPlatformPtr)
		return;

	double lat, lon, alt;
	aPlatformPtr->GetLocationLLA(lat, lon, alt);

	double heading, pitch, roll;
	aPlatformPtr->GetOrientationNED(heading, pitch, roll);


	//拼接json串
	Json::Value root;

	root["MsgType"] = Json::Value("MoverUpdated");
	root["WallTime"] = Json::Value(aSimTime);

	root["PlatformID"] = Json::Value((int)aPlatformPtr->GetIndex());
	root["PlatformName"] = Json::Value(aPlatformPtr->GetName());
	root["PlatformType"] = Json::Value(aPlatformPtr->GetType());
	root["PlatformSide"] = Json::Value(aPlatformPtr->GetSide());


	root["Location"].append(lat);
	root["Location"].append(lon);
	root["Location"].append(alt);

	root["Orientation"].append(heading);
	root["Orientation"].append(pitch);
	root["Orientation"].append(roll);

	Json::FastWriter fw;
	std::string msg = fw.write(root);

	SendPacket(msg);
}
void UDP_Observer::SensorTrackUpdated(double aSimTime, WsfSensor* aSensorPtr, const WsfTrack* aTrackPtr)
{
	double lat, lon, alt;
	aTrackPtr->GetLocationLLA(lat, lon, alt);

	//拼接json串
	Json::Value root;

	root["MsgType"] = Json::Value("SensorTrackUpdate");
	root["WallTime"] = Json::Value(aSimTime);

	root["SensorID"] = Json::Value((int)aSensorPtr->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensorPtr->GetName());
	root["TargetIndex"] = Json::Value(aTrackPtr->GetTargetIndex());


	root["Location"].append(lat);
	root["Location"].append(lon);
	root["Location"].append(alt);


	Json::FastWriter fw;
	std::string msg = fw.write(root);

	SendPacket(msg);
}

// WsfSensorObserver
void UDP_Observer::SensorDetectionAttempt(double aSimTime, WsfSensor* aSensor, WsfPlatform* aPlatform, WsfSensorResult& aResult)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorDetectionAttempt");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());
	root["TargetIndex"] = Json::Value((int)aPlatform->GetIndex());
	root["TargetName"] = Json::Value(aPlatform->GetName());
//	root["DetectionResult"] = Json::Value(aResult.Detected());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorDetectionChanged(double aSimTime, WsfSensor* aSensor, size_t aDetectionIndex, WsfSensorResult& aResult)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorDetectionChanged");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());
	root["DetectionIndex"] = Json::Value((int)aDetectionIndex);
//	root["DetectionResult"] = Json::Value(aResult.Detected());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorOperational(double aSimTime, WsfSensor* aSensor)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorOperational");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());
	root["IsOperational"] = Json::Value(aSensor->IsOperational());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorRequestCanceled(double aSimTime, WsfSensor* aSensor, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorRequestCanceled");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorRequestInitiated(double aSimTime, WsfSensor* aSensor, WsfSensorMode* aMode, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorRequestInitiated");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());
//	root["ModeName"] = Json::Value(aMode->GetName());
//	root["TrackID"] = Json::Value(aTrack->GetTrackId().GetTrackNumber());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorRequestUpdated(double aSimTime, WsfSensor* aSensor, WsfSensorMode* aMode, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorRequestUpdated");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());
	//root["ModeName"] = Json::Value(aMode->GetName());
	//root["TrackID"] = Json::Value(aTrack->GetTrackId().GetTrackNumber());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorScanUpdated(double aSimTime, WsfSensor* aSensor)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorScanUpdated");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}

// WsfSimulationObserver
void UDP_Observer::RequestTimeAdvance(double aSimTime, double aRequestedTime, double aGrantedTime)
{
	Json::Value root;
	root["MsgType"] = Json::Value("RequestTimeAdvance");
	root["WallTime"] = Json::Value(aSimTime);
	root["RequestedTime"] = Json::Value(aRequestedTime);
	root["GrantedTime"] = Json::Value(aGrantedTime);

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationClockRateChange(double aSimTime)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationClockRateChange");
	root["WallTime"] = Json::Value(aSimTime);
	root["ClockRate"] = Json::Value(GetSimulation().GetClockRate());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationInitializing()
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationInitializing");
	root["WallTime"] = Json::Value(GetSimulation().GetSimTime());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationStarting()
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationStarting");
	root["WallTime"] = Json::Value(GetSimulation().GetSimTime());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationPausing()
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationPausing");
	root["WallTime"] = Json::Value(GetSimulation().GetSimTime());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationResuming()
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationResuming");
	root["WallTime"] = Json::Value(GetSimulation().GetSimTime());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SimulationComplete(double aSimTime)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SimulationComplete");
	root["WallTime"] = Json::Value(aSimTime);

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}

// WsfTrackObserver
void UDP_Observer::LocalTrackDropped(double aSimTime, WsfPlatform* aPlatform, const WsfLocalTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("LocalTrackDropped");
	root["WallTime"] = Json::Value(aSimTime);
	root["PlatformID"] = Json::Value((int)aPlatform->GetIndex());
	root["PlatformName"] = Json::Value(aPlatform->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::LocalTrackInitiated(double aSimTime, WsfPlatform* aPlatform, const WsfLocalTrack* aLocalTrack, const WsfTrack* aSensorTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("LocalTrackInitiated");
	root["WallTime"] = Json::Value(aSimTime);
	root["PlatformID"] = Json::Value((int)aPlatform->GetIndex());
	root["PlatformName"] = Json::Value(aPlatform->GetName());
	//root["trackName"] = Json::Value(1);

	//////获取轨迹
	//unsigned int trackId1 = aPlatform->GetTrackManager().GetRawTrackCount();
	//unsigned int trackId2 = aPlatform->GetTrackManager().GetTrackCount();
	//root["trackName1"] = Json::Value(trackId1);
	//root["trackName2"] = Json::Value(trackId2);
	//WsfTrack* track = aPlatform->GetTrackManager().GetTrackEntry(trackId2 - 1);
	//if (!track)
	//	ut::log::info() << "err no track";
	//else
	//	root["trackName"] = Json::Value(track->GetTargetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::LocalTrackUpdated(double aSimTime, WsfPlatform* aPlatform, const WsfLocalTrack* aLocalTrack, const WsfTrack* aSensorTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("LocalTrackUpdated");
	root["WallTime"] = Json::Value(aSimTime);
	root["PlatformID"] = Json::Value((int)aPlatform->GetIndex());
	root["PlatformName"] = Json::Value(aPlatform->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorTrackCoasted(double aSimTime, WsfSensor* aSensor, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorTrackCoasted");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorTrackDropped(double aSimTime, WsfSensor* aSensor, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorTrackDropped");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::SensorTrackInitiated(double aSimTime, WsfSensor* aSensor, const WsfTrack* aTrack)
{
	Json::Value root;
	root["MsgType"] = Json::Value("SensorTrackInitiated");
	root["WallTime"] = Json::Value(aSimTime);
	root["SensorID"] = Json::Value((int)aSensor->GetPlatform()->GetIndex());
	root["SensorName"] = Json::Value(aSensor->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}

// WsfWeaponObserver
void UDP_Observer::WeaponFireAborted(double aSimTime, WsfWeapon* aWeapon, const WsfTrack* aTrack, double aTime)
{
	Json::Value root;
	root["MsgType"] = Json::Value("WeaponFireAborted");
	root["WallTime"] = Json::Value(aSimTime);
	root["WeaponName"] = Json::Value(aWeapon->GetName());
	root["TargetIndex"] = Json::Value(aTrack->GetTargetIndex());
	root["FireTime"] = Json::Value(aTime);

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::WeaponFired(double aSimTime, const WsfWeaponEngagement* aEngagement, const WsfTrack* aTrack)
{
}
void UDP_Observer::WeaponFireRequested(double aSimTime, WsfWeapon* aWeapon, const WsfTrack* aTrack, double aTime)
{
	Json::Value root;
}
void UDP_Observer::WeaponPlatformPendingAdd(double aSimTime, WsfPlatform* aPlatform, const WsfWeaponEngagement* aEngagement, const WsfTrack* aTrack)
{
}
void UDP_Observer::WeaponHit(double aSimTime, const WsfWeaponEngagement* aEngagement, WsfPlatform* aTarget)
{
}
void UDP_Observer::WeaponKilled(double aSimTime, WsfWeapon* aWeapon)
{
	Json::Value root;
	root["MsgType"] = Json::Value("WeaponKilled");
	root["WallTime"] = Json::Value(aSimTime);
	root["WeaponID"] = Json::Value((int)aWeapon->GetPlatform()->GetIndex());
	root["WeaponName"] = Json::Value(aWeapon->GetName());

	Json::FastWriter fw;
	std::string msg = fw.write(root);
	SendPacket(msg);
}
void UDP_Observer::WeaponMissed(double aSimTime, const WsfWeaponEngagement* aEngagement, WsfPlatform* aTarget)
{
}

//辅助函数
Json::Value UDP_Observer::GenerateSimulationData(double aSimTime)
{
	Json::Value simulationData;

	Json::Value simulationTime;
	double startTime = GetSimulation().GetDateTime().GetStartTime();
	double currentTime = GetSimulation().GetSimTime();
	double stepTime = GetSimulation().GetTimestep();
	simulationTime["BeginTime"] = startTime;
	simulationTime["CurrentTime"] = currentTime;
	simulationTime["CurrentStep"] = stepTime;
	simulationData["SimulationTime"] = simulationTime;

	Json::Value simulationSide;
	std::map<std::string, Json::Value> sideMap;
	for (const auto& platformInfo : mPlatformSides)
	{
		std::string side = platformInfo.side;
		int index = platformInfo.index;

		// 如果该阵营尚未处理，则创建新的SimSide结构
		if (sideMap.find(side) == sideMap.end())
		{
			Json::Value simSide;
			simSide["ID"] = side; // 使用阵营名称作为ID
			simSide["Name"] = side; // 阵营名称
			simSide["Postures"] = Json::Value(Json::objectValue); // 空对象，无法获取对立关系
			simSide["CombatUnits"] = Json::Value(Json::arrayValue); // 作战单元数组
			simSide["Contacts"] = Json::Value(Json::arrayValue); // 探测单元数组（保持为空）
			simSide["CombatAreas"] = Json::Value(Json::arrayValue); // 空数组，非必填
			simSide["AreaPoints"] = Json::Value(Json::arrayValue); // 空数组，非必填

			sideMap[side] = simSide;
		}

		WsfPlatform* platform = GetSimulation().GetPlatformByIndex(index);
		if (!platform)
			continue;

		Json::Value combatUnit = CreateCombatUnit(platform);
		sideMap[side]["CombatUnits"].append(combatUnit);
	}

	for (auto& sidePair : sideMap)
	{
		simulationSide.append(sidePair.second);
	}

	simulationData["SimulationSide"] = simulationSide;
	return simulationData;
}
std::string UDP_Observer::ConvertTimeToISOString(double simTime)
{
	time_t rawTime = static_cast<time_t>(simTime);
	struct tm* timeInfo = gmtime(&rawTime);

	char buffer[30];
	strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", timeInfo);

	return std::string(buffer);
}
Json::Value UDP_Observer::CreateCombatUnit(WsfPlatform* platform)
{
	Json::Value unit;

	unit["ID"] = std::to_string(platform->GetIndex());
	unit["Name"] = platform->GetName().substr(0, 30);
	unit["Sidename"] = platform->GetSide();
	unit["DbId"] = ""; // 数据库ID（无法获取）
	unit["Model"] = ""; // 设备型号（无法获取）
	unit["Type"] = ""; // 单元类型（无法获取枚举值）

	Json::Value location;
	double curlocationp[3] = {};
	bool ok = platform->GetMover()->GetFutureLocationWCS(GetSimulation().GetWallTime(), curlocationp);
	if (!ok)
		ut::log::info() << "getlocation error";

	location["Lot"] = curlocationp[1];
	location["Lat"] = curlocationp[2];
	location["Alt"] = curlocationp[3];
	unit["Location"] = location;

	Json::Value attitude;
	attitude["Yaw"] = 0.0;   // 偏航
	attitude["Roll"] = 0.0;  // 滚转
	attitude["Pitch"] = 0.0; // 俯仰
	unit["Attitude"] = attitude;

	unit["Speed"] = platform->GetSpeed();

	unit["WeaponData"] = Json::Value(Json::objectValue);
	unit["BaseId"] = "";
	unit["Health"] = 100;

	// 任务ID（非必填，设为空）
	unit["MissionId"] = "";

	unit["UnitStatus"] = "待命";
	unit["AirUnitStatus"] = Json::Value(Json::objectValue);

	// 是否可被自动探测（必填，默认是）
	unit["AutoDetectable"] = true;

	// 挂载武器列表（必填，至少1个）
	Json::Value mountWeapons(Json::arrayValue);
	Json::Value defaultWeapon;
	defaultWeapon["ID"] = "weapon_default";
	defaultWeapon["Name"] = "Default Weapon";
	defaultWeapon["Type"] = "Unknown";
	defaultWeapon["Count"] = 1;
	mountWeapons.append(defaultWeapon);
	unit["MountWeapons"] = mountWeapons;

	// 燃油情况（必填）
	Json::Value fuelStatus;
	fuelStatus["Current"] = 100.0; // 当前燃油百分比
	fuelStatus["Max"] = 100.0;    // 最大燃油量
	fuelStatus["ConsumptionRate"] = 0.0; // 消耗率
	unit["FuelStatus"] = fuelStatus;

	// 传感器状态列表（必填，至少1个）
	Json::Value sensorStatus(Json::arrayValue);
	Json::Value defaultSensor;
	defaultSensor["ID"] = "sensor_default";
	defaultSensor["Name"] = "Default Sensor";
	defaultSensor["Type"] = "Unknown";
	defaultSensor["Status"] = "Operational";
	sensorStatus.append(defaultSensor);
	unit["SensorStatus"] = sensorStatus;

	// 搭载对象（必填）
	Json::Value carryUnits(Json::arrayValue);
	Json::Value defaultCarryUnit;
	defaultCarryUnit["ID"] = "carry_unit_default";
	defaultCarryUnit["Name"] = "Default Carry Unit";
	defaultCarryUnit["Type"] = "Unknown";
	carryUnits.append(defaultCarryUnit);
	unit["CarryUnits"] = carryUnits;

	return unit;
}
void UDP_Observer::SendPacket(const std::string& aMessage)
{
	int bytesWritten = mConnectionPtr->SendBuffer(aMessage.c_str(), ut::cast_to_int(aMessage.length() + 1));
	if (bytesWritten < 0)
	{
		ut::log::error() << "Socket error: " << GenSockets::GenSocketManager::GetLastError();
		Disconnect();
	}
}